<script setup lang="ts">
import { ref, onMounted } from 'vue';
import apiClient from '@/api.ts';
import { useRouter } from 'vue-router';

interface Post {
  id: number;
  title: string;
  created_at: string;
}

const posts = ref<Post[]>([]);
const router = useRouter();

const fetchPosts = async () => {
  try {
    const response = await apiClient.get('/api/posts');
    posts.value = response.data;
  } catch (error) {
    console.error('Failed to fetch posts:', error);
  }
};

const deletePost = async (id: number) => {
  if (confirm('您确定要删除这篇文章吗？')) {
    try {
      await apiClient.delete(`/api/posts/${id}`);
      fetchPosts(); // Refresh the list
    } catch (error) {
      console.error('删除文章失败:', error);
      alert('删除文章失败。');
    }
  }
};

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};

onMounted(fetchPosts);
</script>

<template>
  <div class="posts-management">
    <div class="header">
      <h1>文章管理</h1>
      <button @click="router.push('/admin/posts/new')">新建文章</button>
    </div>
    <table>
      <thead>
        <tr>
          <th>标题</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="posts.length === 0">
          <td colspan="3">暂无文章。</td>
        </tr>
        <tr v-for="post in posts" :key="post.id">
          <td>{{ post.title }}</td>
          <td>{{ formatDate(post.created_at) }}</td>
          <td class="actions">
            <button @click="router.push(`/admin/posts/edit/${post.id}`)">编辑</button>
            <button class="delete" @click="deletePost(post.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
.posts-management {
  animation: fadeIn 0.5s;
}
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}
h1 {
  margin: 0;
}
button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  background-color: var(--color-primary);
  color: white;
  cursor: pointer;
}
table {
  width: 100%;
  border-collapse: collapse;
  background: var(--color-background-soft);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
th, td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid var(--color-border);
}
th {
  background-color: var(--color-background-mute);
}
.actions button {
  margin-right: 0.5rem;
}
.actions button.delete {
  background-color: #e74c3c;
}
.actions button.delete:hover {
  background-color: #c0392b;
}
</style>